import {
  wxRequest
} from '../../utils/server.js';
const _wxRequest = new wxRequest();
const app = getApp()
const bluetooth = require('../../utils/bluetooth');
const NewBluetooth = require('../../utils/newBluetooth');
import RgjBleHelper from '../../utils/ble/RgjBleHelper.js'
let newBluetooth = new NewBluetooth();
let commitId = 0;
let hasFindBlue = false;
// 轮询接口 查询提交状态
// 轮询次数
let requestCount = 3;
// 轮询持续时间(ms)
let requestTotalTime = 10000;
// 轮询定时器ID
let intervalId = 0;
// 轮询间隔
let intervalTime = requestTotalTime / requestCount;

// 蓝牙后
let onBlueStartRequest = {
  requestSend: false,
  requestCount: 3,
  requestTotalTime: 10000,
  requestIntervalId: 0,
  requestSendA6: false,
  deviceResponse: false,
  hasSend0080: false,
  hasSend00B0: false
}

onBlueStartRequest.requestIntervalTime = onBlueStartRequest.requestTotalTime / onBlueStartRequest.requestCount

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: app.globalData.imgUrl,
    device: {},
    typeIndex: 0,
    deviceList: [],
    typeId: '',
    uploadUrl: wx.getStorageSync('uploadUrl'),
    bluetoothDeviceList: [],
		mac: '',
    btid: '',
    // 是否是mini机型
    isMini: wx.getStorageSync('isMini'),
    // 蓝牙实例
    rgjBleHelper: {},
    deviceInfo: []
  },

  onShow: function (options) {
    this.setData({
      typeId: wx.getStorageSync('currentTypeId')
    })
    this.getDeviceList()
  },
  initRgjBleHelper(list, type) {
    this.data.rgjBleHelper = new RgjBleHelper({
      mac: this.data.deviceList[this.data.typeIndex].code,
      statusChangeCallback: async (status) => {
        console.log(status)
        wx.hideLoading()
        this.resetBlueRequest();
        this.resetRequest();
        if (status == RgjBleHelper.BLUE_DYE_COLOR_TIMEOUT) {
          wx.showToast({
            title: '超时!',
            icon: 'none'
          })
          this.data.rgjBleHelper.initBLEStatus()
        }
        if (status == RgjBleHelper.BLUE_DYE_COLOR_FINISH) {
          wx.showToast({
            title: '成功！',
            icon: 'none'
          })
          this.data.rgjBleHelper.initBLEStatus()
        }
        if (status == RgjBleHelper.BLUE_DYE_COLOR_FAILED) {
          wx.showToast({
            title: '失败，请重试！',
            icon: 'none'
          })
          this.data.rgjBleHelper.initBLEStatus()
        }
        if (status == RgjBleHelper.BLUE_SERVICE_FAILED || status == RgjBleHelper.BLUE_STATUS_FAILED) {
          wx.hideLoading()
          this.data.rgjBleHelper.initBLEStatus()
        }
      }
    })
    this.data.rgjBleHelper.initBlue(this.data.deviceList[this.data.typeIndex].code)
  },

  scanCodeClick: function (e) {
    var that = this;
    return new Promise(async (resolve, reject) => {
      // 初始化蓝牙
      try {
        //等待蓝牙状态返回
        await newBluetooth.initScanBluetoothDevice();
        newBluetooth.startScanDevice();
        let foundedDevice = await newBluetooth.getBlueDevice();
        let bluetoothDeviceList = that.data.bluetoothDeviceList;
        bluetoothDeviceList = bluetoothDeviceList.concat(foundedDevice.devices);
        that.setData({
          bluetoothDeviceList
        });
        //没有蓝牙地址  查找蓝牙列表中 是否有名称为mac的设备
        newBluetooth.listenOnDeviceFounded(res => {
          let bluetoothDeviceList = that.data.bluetoothDeviceList;
          bluetoothDeviceList = bluetoothDeviceList.concat(res.devices);
          that.setData({
            bluetoothDeviceList
          });
          let findDevice = bluetoothDeviceList.filter(item => item.name == that.data.deviceList[that.data.typeIndex].code);
          if (findDevice.length > 0) {
            that.setData({
              btid: findDevice[0].deviceId
            })
            resolve();

          }
        });
      } catch (e) {

        console.log(e);
        if (e.errCode == 10001) {
          wx.showToast({
            icon: 'none',
            title: '请打开蓝牙'
          })
        }
        reject();
      }
    })
  },

  findBlue(str) {
    var that = this;
    //链接蓝牙
    console.log("开始连接蓝牙", this.data.deviceList[this.data.typeIndex].code, this.data.btid);
    bluetooth.bluetooth.openBlue(this.data.deviceList[this.data.typeIndex].code, this.data.btid,
      function (_res) {
        that.setData({
          conn_msg: _res
        });
        bluetooth.bluetooth.set_down_hex(str);
        //bluetooth.bluetooth.write_value(str);
      },
      function (_res) {
        // 写入成功回调

        // 如果写入00b0
        console.log('写入数据00b0：', _res, _res.toLowerCase(), onBlueStartRequest.hasSend00B0);
        if (_res.toLowerCase().indexOf('660000b0') == 0 && !onBlueStartRequest.hasSend00B0) {
          // 标记为已发送00B0
          onBlueStartRequest.hasSend00B0 = true;

          setTimeout(() => {
            // 如果2s之后设备没回复00B0， 则开始服务器轮询
            if (!onBlueStartRequest.requestSend) {
              // 如果写入没有发起轮询 则发起轮询
              wx.showLoading({
                title: '查询结果中...',
              })
              onBlueStartRequest.requestIntervalId = setInterval(() => {
                // 轮询请求
                _wxRequest.wxTonkenAjax({
                  loading: false,
                  url: app.globalData.apiUrl + '/gds/protected/dyeRecord/getById/' + commitId,
                  method: 'GET'
                }, async (res1) => {
                  let dyeRecord = res1.vo;
                  let isSuccess = dyeRecord.status == 21 || dyeRecord.status == 0 || dyeRecord.status == 13;
                  if (onBlueStartRequest.requestCount <= 0 && !isSuccess) {
                    wx.hideLoading();
                    // 后台自动判断是否下发
                    wx.showModal({
                      title: '提示',
                      content: '本次换料未有结果',
                      showCancel: false,
                      success: async (confirmRes) => {
                        wx.navigateBack({
                          delta: 0,
                        })
                        that.closeBlueFea();
                      }
                    })
                    that.resetBlueRequest();
                  } else {
                    if (res1.vo) {
                      // wx.showLoading({
                      // 	title: '查询结果中...',
                      // })
                      // 如果不是等待中 说明已有结果
                      if (isSuccess) {

                        if (dyeRecord.status == 0) {
                          wx.hideLoading();
                          // 状态异常弹窗提示
                          wx.showToast({
                            duration: 3000,
                            icon: 'none',
                            title: dyeRecord.note,
                          })
                          // that.closeBlueFea();
                          // console.log('关闭的定时器ID', onBlueStartRequest.requestIntervalId)
                          // // 结束轮询
                          // clearInterval(onBlueStartRequest.requestIntervalId);
                          // // 
                          // that.resetRequest();
                          // that.resetBlueRequest();
                        }

                        wx.hideLoading();
                        console.log('后台已有结果，当前A6发送状态', onBlueStartRequest.requestSendA6);
                        // 后台已有回调结果 发送A6给设备获取0080指令
                        onBlueStartRequest.requestSendA6 = true;
                        bluetooth.bluetooth.write_value("A6");
                        // 结束轮询
                        clearInterval(onBlueStartRequest.requestIntervalId);
                      }
                    }
                  }
                  onBlueStartRequest.requestCount--;
                })
              }, onBlueStartRequest.requestIntervalTime);
              console.log('开启定时器', onBlueStartRequest.requestIntervalId);
              // 修改为已发起
              onBlueStartRequest.requestSend = true;
            }
          }, 5000);
        }

        if (_res.toLowerCase().indexOf('66000080') == 0 && !onBlueStartRequest.hasSend0080) {
          // 标记为已发送0080
          console.log('写入数据0080：', _res);
          onBlueStartRequest.hasSend0080 = true;
          setTimeout(() => {
            wx.showToast({
              title: '换料成功',
              success: () => {
                setTimeout(() => {
                  that.resetBlueRequest();
                  wx.navigateBack({
                    delta: 0,
                  })
                  that.resetRequest();
                }, 1000);
              }
            })

          }, 1000);
        }


      },
      function (_res) {
        console.log('收到数据：', _res);
        if (_res.toLowerCase().indexOf("660000b0") == 0) {
          onBlueStartRequest.deviceResponse = true;
          console.log('收到设备的00B0，下传A6采集数据')
          setTimeout(() => {
            console.log('后台无结果2s后无结果，当前A6状态', onBlueStartRequest.requestSendA6);
            if (!onBlueStartRequest.requestSendA6) {
              bluetooth.bluetooth.write_value("A6");
              onBlueStartRequest.requestSendA6 = true;
            }
          }, 2000)
        }

        if (_res.toLowerCase().indexOf('66000080') == 0) {
          // 检测到下料已经成功  关闭蓝牙
          // bluetooth.bluetooth.write_no();
          // bluetooth.bluetooth.close_bt(that.data.btid, function(res) {
          //   console.log("关闭蓝牙成功：" + res);
          // }, function(res) {
          //   console.log("关闭蓝牙错误：" + res);
          // });
          if (onBlueStartRequest.requestSendA6) {
            if (onBlueStartRequest.hasSend0080) {
              wx.showToast({
                title: '换料成功',
              })
              that.resetBlueRequest();
              wx.navigateBack({
                delta: 0,
              })
            }

          }

        }
      },
			function(res2) {
				console.log('广播通知绑定成功')
				if(!hasFindBlue) {
					bluetooth.bluetooth.write_value(str);
					hasFindBlue = true
				}
				
			}
    );
  },


  //获取记录列表
  dyeRecord: function () {
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/dyeRecord/findDyeList',
      method: 'POST',
      data: {
        devId: this.data.deviceList[this.data.typeIndex].id,
        pageNo: 1,
        pageSize: 50,
        keyword: this.data.keyword,
      }
    }, (res) => {
      let list = res.list;
      this.setData({
        recodeList: list,
      });
    })
  },

  resetRequest() {
    clearInterval(intervalId);
    // 轮询接口 查询提交状态
    // 轮询次数
    requestCount = 3;
    // 轮询持续时间(ms)
    requestTotalTime = 6000;
    // 轮询定时器ID
    intervalId = 0;
    // 轮询间隔
    intervalTime = requestTotalTime / requestCount;
  },

  resetBlueRequest() {
		clearInterval(onBlueStartRequest.requestIntervalId);
		onBlueStartRequest = {
			requestSend: false,
			requestCount: 3,
			requestTotalTime: 10000,
			requestIntervalId: 0,
			requestSendA6: false,
			deviceResponse: false,
			hasSend0080: false,
			hasSend00B0: false
		}

		onBlueStartRequest.requestIntervalTime = onBlueStartRequest.requestTotalTime / onBlueStartRequest.requestCount
	},

  onHide: function () {
    this.data.rgjBleHelper.initBLEStatus()
    this.resetRequest();
    this.resetBlueRequest();
    this.closeBlueFea();
    hasFindBlue = false;
	},

	closeBlueFea() {
		newBluetooth.stopBluetoothScan();
		bluetooth.bluetooth.write_no();
		bluetooth.bluetooth.close_bt(this.data.btid, function (res) {
			console.log("关闭蓝牙成功：" + res);
		}, function (res) {
			console.log("关闭蓝牙错误：" + res);
		});
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
    this.data.rgjBleHelper.initBLEStatus()
		this.resetRequest();
    this.resetBlueRequest();
    this.closeBlueFea();
    hasFindBlue = false;
	},

  startCompeleteContinue() {
    var params = {
      recType: 4,
      devId: this.data.deviceList[this.data.typeIndex].id,
      status: 21
    }
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/dyeRecord/create',
      method: 'POST',
      data: params,
    }, (res) => {
      // wx.showToast({
      //   title: '请求成功',
      // })
      // wx.navigateBack({
      //   delta: 0,
      // })
      // wx.showLoading({
      // 	title: '等待结果中',
      // })

      if (!res.data.id) {

        return;
      }
      commitId = res.data.id;
      wx.showLoading({
        title: '查询结果中...',
      })
      intervalId = setInterval(() => {
        // 轮询请求
        _wxRequest.wxTonkenAjax({
          loading: false,
          url: app.globalData.apiUrl + '/gds/protected/dyeRecord/getById/' + res.data.id,
          method: 'GET'
        }, async (res1) => {
          let dyeRecord = res1.vo;
          let isSuccess = dyeRecord.status == 21 || dyeRecord.status == 0 || dyeRecord.status == 13;

          if (requestCount < 1 && !isSuccess) {
            // 轮询结束 还没跳转 用蓝牙补发
            // 后台自动判断是否下发
            wx.hideLoading();
            wx.showModal({
              title: '提示',
              content: '设备当前信号弱，将使用线下模式，请打开蓝牙并且确保距离设备1米以内',
              success: async (confirmRes) => {

                if (confirmRes.confirm) {
                  wx.showLoading({
                    title: '正在连接设备',
                  })
                  if (this.data.isMini) {
                    await this.scanCodeClick();
                    this.findBlue(res.data.hex);
                  } else {
                    this.data.rgjBleHelper.startReloadDyeColor(this.data.deviceList[this.data.typeIndex].code, 1)
                  }
                }
              }
            })
            this.resetRequest();
          } else {
            if (isSuccess) {
              if (dyeRecord.status == 0) {
                wx.showToast({
                  duration: 3000,
                  icon: 'none',
                  title: dyeRecord.note,
                })
              }
              //wx.hideLoading();
              // 调色已由物联网发送完成 直接跳转到调色记录即可
              wx.navigateBack({
                delta: 0,
              })
              clearInterval(intervalId);
            }
          }
          requestCount--;
        })

      }, intervalTime);
    })
  },

  startCompelete() {
    var params = {
      recType: 4,
      devId: this.data.deviceList[this.data.typeIndex].id,
      status: 20
    }
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/dyeRecord/create',
      method: 'POST',
      data: params,
    }, (res) => {
     // wx.showToast({
      //   title: '请求成功',
      // })
      // wx.navigateBack({
      //   delta: 0,
      // })
      // wx.showLoading({
      // 	title: '等待结果中',
      // })

      if (!res.data.id) {

        return;
      }
      commitId = res.data.id;
      wx.showLoading({
        title: '查询结果中...',
      })
      intervalId = setInterval(() => {
        // 轮询请求
        _wxRequest.wxTonkenAjax({
          loading: false,
          url: app.globalData.apiUrl + '/gds/protected/dyeRecord/getById/' + res.data.id,
          method: 'GET'
        }, async (res1) => {
          let dyeRecord = res1.vo;
          let isSuccess = dyeRecord.status == 21 || dyeRecord.status == 0 || dyeRecord.status == 13;

          if (requestCount < 1 && !isSuccess) {
            // 轮询结束 还没跳转 用蓝牙补发
            // 后台自动判断是否下发
            //wx.hideLoading();
            wx.showModal({
              title: '提示',
              content: '设备当前信号弱，将使用线下模式，请打开蓝牙并且确保距离设备1米以内',
              success: async (confirmRes) => {

                if (confirmRes.confirm) {
                  wx.showLoading({
                    title: '正在连接设备',
                  })
                  if (this.data.isMini) {
                    await this.scanCodeClick();
                    this.findBlue(res.data.hex);
                  } else {
                    this.data.rgjBleHelper.startReloadDyeColor(this.data.deviceList[this.data.typeIndex].code, 2)
                  }
                }
              }
            })
            this.resetRequest();
          } else {
            if (isSuccess) {
              if (dyeRecord.status == 0) {
                wx.showToast({
                  duration: 3000,
                  icon: 'none',
                  title: dyeRecord.note,
                })
              }
              wx.hideLoading();
              // 调色已由物联网发送完成 直接跳转到调色记录即可
              wx.navigateBack({
                delta: 0,
              })
              clearInterval(intervalId);
            }
          }
          requestCount--;
        })

      }, intervalTime);
    })
  },



  //触底时，加载更多
  onReachBottom: function () {
    if (this.data.hasNextPage) {
      this.setData({
        pageNo: this.data.pageNo + 1
      });
      this.dyeRecord();
    }
  },

  //搜索关键词
  seachInputConfirm: function (e) {
    this.setData({
      pageNo: 1,
      keyword: e.detail.value
    })
    this.dyeRecord();
  },

  seachBtn: function () {
    this.setData({
      pageNo: 1,
      keyword: this.data.keyword
    })
    this.dyeRecord();
  },

  seachInputVal: function (e) {
    var inputval = e.detail.value;
    console.log(e)
    this.setData({
      keyword: inputval
    })
  },

  //清空
  clearInput: function () {
    this.setData({
      keyword: ''
    })
    this.dyeRecord();
  },




  //详情
  toDetail: function (e) {
    var item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: '/pages/color_residue/detail?id=' + item.id,
    })
  },








  bindPickerChange(e) {
    var val = e.detail.value
    this.setData({
      typeIndex: val
    }, () => {
      this.dyeRecord();
    })
  },






  getDeviceList: function () {
    var params = {
      keyword: this.data.keyword,
      pageNo: 1,
      typeId: this.data.typeId,
      pageSize: 999
    }

    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/device/findList',
      method: 'POST',
      data: params
    }, (res) => {
      let list = res.list.map(item => {
        if (item.stoName) {
          item.note += ` - ${item.stoName}`;
        }

        if (item.stoCreateName) {
          item.note += ` - ${item.stoCreateName}`;
        }
        return item;
      });
      console.log(list);
      let devId = wx.getStorageSync('devId')
      if (devId) {
        this.data.typeIndex = list.findIndex(item => item.id === devId)
        this.data.deviceInfo = list.filter(item => item.id == devId)
      }
      console.log(this.data.deviceInfo,123);
      this.setData({
        deviceList: list,
        typeIndex: this.data.typeIndex
      }, () => {
        if (list.length > 0) {
          this.dyeRecord()
          this.initRgjBleHelper(list, this.data.typeIndex)
        }

      });
    })
  },




})